"""
比对性能基准测试

比较原方法和高性能方法的性能差异
"""

import numpy as np
import time
import psutil
import os
from memory_profiler import memory_usage
from high_performance_comparer import HighPerformanceComparer
import matplotlib.pyplot as plt
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def create_test_data(num_frames, num_vc=4):
    """创建测试数据"""
    frames = []
    for i in range(num_frames):
        frame = {
            'frame_count': i,
            'virtual_channel': i % num_vc,
            'payload': np.random.bytes(1024),
            'decode_status': 0
        }
        frames.append(frame)
    return frames


def measure_memory_usage(func, *args, **kwargs):
    """测量函数的内存使用"""
    mem_usage = memory_usage((func, args, kwargs))
    return max(mem_usage) - min(mem_usage)


def benchmark_standard_method(frames1, frames2):
    """标准方法基准测试（简化版）"""
    start_time = time.time()
    
    # 模拟原有的逐帧比对逻辑
    matching = 0
    for f1, f2 in zip(frames1, frames2):
        if f1['payload'] == f2['payload']:
            matching += 1
    
    elapsed = time.time() - start_time
    return elapsed, matching


def benchmark_high_performance_method(frames1, frames2):
    """高性能方法基准测试"""
    comparer = HighPerformanceComparer()
    
    start_time = time.time()
    result = comparer.compare_files_vectorized(
        frames1, frames2,
        use_multiprocessing=False  # 公平比较，都使用单进程
    )
    elapsed = time.time() - start_time
    
    return elapsed, result['matching_frames']


def run_benchmarks():
    """运行基准测试"""
    test_sizes = [100, 500, 1000, 5000, 10000, 20000]
    standard_times = []
    hp_times = []
    speedups = []
    
    logger.info("开始性能基准测试...\n")
    logger.info(f"{'帧数':>8} | {'标准方法':>10} | {'高性能方法':>10} | {'加速比':>8}")
    logger.info("-" * 50)
    
    for size in test_sizes:
        # 创建测试数据
        frames1 = create_test_data(size)
        frames2 = create_test_data(size)
        
        # 标准方法
        std_time, std_match = benchmark_standard_method(frames1, frames2)
        standard_times.append(std_time)
        
        # 高性能方法
        hp_time, hp_match = benchmark_high_performance_method(frames1, frames2)
        hp_times.append(hp_time)
        
        # 计算加速比
        speedup = std_time / hp_time if hp_time > 0 else 0
        speedups.append(speedup)
        
        logger.info(f"{size:>8} | {std_time:>10.3f}s | {hp_time:>10.3f}s | {speedup:>8.1f}x")
    
    # 绘制性能对比图
    plt.figure(figsize=(12, 5))
    
    # 子图1：执行时间对比
    plt.subplot(1, 2, 1)
    plt.plot(test_sizes, standard_times, 'b-o', label='标准方法')
    plt.plot(test_sizes, hp_times, 'r-o', label='高性能方法')
    plt.xlabel('帧数')
    plt.ylabel('执行时间 (秒)')
    plt.title('执行时间对比')
    plt.legend()
    plt.grid(True)
    plt.yscale('log')
    
    # 子图2：加速比
    plt.subplot(1, 2, 2)
    plt.bar(range(len(test_sizes)), speedups, tick_label=test_sizes)
    plt.xlabel('帧数')
    plt.ylabel('加速比')
    plt.title('性能提升倍数')
    plt.grid(True, axis='y')
    
    # 在柱状图上添加数值标签
    for i, v in enumerate(speedups):
        plt.text(i, v + 0.5, f'{v:.1f}x', ha='center')
    
    plt.tight_layout()
    plt.savefig('performance_comparison.png')
    logger.info(f"\n性能对比图已保存为 performance_comparison.png")
    
    # 计算平均加速比
    avg_speedup = sum(speedups) / len(speedups)
    logger.info(f"\n平均加速比: {avg_speedup:.1f}x")
    
    # 内存使用对比
    logger.info("\n内存使用对比 (10000帧数据):")
    
    # 创建测试数据
    frames1 = create_test_data(10000)
    frames2 = create_test_data(10000)
    
    # 测量内存使用
    std_mem = measure_memory_usage(benchmark_standard_method, frames1, frames2)
    hp_mem = measure_memory_usage(benchmark_high_performance_method, frames1, frames2)
    
    logger.info(f"标准方法内存使用: {std_mem:.1f} MB")
    logger.info(f"高性能方法内存使用: {hp_mem:.1f} MB")
    logger.info(f"内存效率提升: {(1 - hp_mem/std_mem)*100:.1f}%")
    
    return {
        'test_sizes': test_sizes,
        'standard_times': standard_times,
        'hp_times': hp_times,
        'speedups': speedups,
        'avg_speedup': avg_speedup,
        'memory_standard': std_mem,
        'memory_hp': hp_mem
    }


def test_multiprocessing_benefit():
    """测试多进程的性能提升"""
    logger.info("\n\n多进程性能测试...")
    
    # 创建大数据集
    frames1 = create_test_data(50000, num_vc=8)
    frames2 = create_test_data(50000, num_vc=8)
    
    comparer = HighPerformanceComparer()
    
    # 单进程测试
    start_time = time.time()
    result_single = comparer.compare_files_vectorized(
        frames1, frames2,
        use_multiprocessing=False
    )
    single_time = time.time() - start_time
    
    # 多进程测试
    start_time = time.time()
    result_multi = comparer.compare_files_vectorized(
        frames1, frames2,
        use_multiprocessing=True
    )
    multi_time = time.time() - start_time
    
    logger.info(f"单进程耗时: {single_time:.3f}s")
    logger.info(f"多进程耗时: {multi_time:.3f}s")
    logger.info(f"多进程加速比: {single_time/multi_time:.1f}x")
    logger.info(f"CPU核心数: {os.cpu_count()}")


if __name__ == "__main__":
    # 检查是否安装了memory_profiler
    try:
        from memory_profiler import memory_usage
        
        # 运行基准测试
        results = run_benchmarks()
        
        # 测试多进程性能
        test_multiprocessing_benefit()
        
        logger.info("\n✅ 基准测试完成！")
        
    except ImportError:
        logger.warning("请安装memory_profiler: pip install memory-profiler")
        logger.info("运行简化版基准测试...")
        
        # 运行不需要memory_profiler的简化版测试
        test_sizes = [100, 1000, 10000]
        
        for size in test_sizes:
            frames1 = create_test_data(size)
            frames2 = create_test_data(size)
            
            # 标准方法
            std_time, _ = benchmark_standard_method(frames1, frames2)
            
            # 高性能方法
            hp_time, _ = benchmark_high_performance_method(frames1, frames2)
            
            speedup = std_time / hp_time
            logger.info(f"帧数 {size}: 标准方法 {std_time:.3f}s, "
                       f"高性能方法 {hp_time:.3f}s, 加速 {speedup:.1f}x") 